package com.info.zhiduoduo.pay.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.info.zhiduoduo.common.configs.PingAnPayConfig;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.pay.formbean.pinganpay.*;
import com.info.zhiduoduo.pay.sdk.pinganbank.model.response.*;
import com.info.zhiduoduo.repository.entity.pay.PaymentMerchant;
import com.pingan.openbank.api.sdk.client.ApiClient;
import com.pingan.openbank.api.sdk.common.http.HttpResult;
import com.pingan.openbank.api.sdk.entity.SdkRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import proguard.util.StringUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 平安银行支付
 */
@Slf4j
@Service
public class PinganBankPayService {
    @Resource
    private PingAnPayConfig pingAnPayConfig;

    private static ApiClient apiClient = ApiClient.getInstance("pingan-rushan-prod.properties");

    /**
     * 平安银行查询账号接口 BEDL_4001
     *
     * @param formBean
     * @return
     */
    public SmartResult balanceQuery(PinganQueryFormBean formBean) {
        SmartResult smartResult = new SmartResult();
        PaymentMerchant paymentMerchant = new PaymentMerchant().selectById(formBean.getPaymentMerchant());
//        String caFile = paymentMerchant.getCaFile();
//        ApiClient apiClient = ApiClient.getInstance(caFile);
        JSONObject requestBody = new JSONObject();
        //系统流水号，规范：用户短号（6位）+日期（6位）+随机编号（10位）
        String cnsmrSeqNo = RandomUtil.createRandomNoForPingan("", "");
        requestBody.put("CnsmrSeqNo", cnsmrSeqNo);
        requestBody.put("Account", paymentMerchant.getBankCard());
        System.out.println("requestBody=" + requestBody);
        SdkRequest sdkRequest = new SdkRequest();
        sdkRequest.setInterfaceName("V1.0/bedl/CorAcctBalanceQuery");
        sdkRequest.setBody(requestBody);
        HttpResult httpResult = apiClient.invoke(sdkRequest);
        if (httpResult.isSuccess()) {
            String data = httpResult.getData();
            log.info("平安银行查询账号接口 CnsmrSeqNo: {} BEDL_4001 返回:{}", cnsmrSeqNo, data);
            JSONObject jsonObject = JSON.parseObject(data);
            //错误返回报文: {"Errors":[{"ErrorCode":"YQ9990","ErrorMessage":":企业本账户没有开通此交易V2！Qydm20[0090108000000YC00000]UBN_ACCT[150001014678471]TRANS"}],"Message":"业务处理失败（通讯成功）","Code":"E50000"}
            String code = jsonObject.getString("Code");
            if (null != code) {
                smartResult.setState(256);
                smartResult.setMsg(jsonObject.getString("Message"));
                return smartResult;
            }
            BalanceQuery balanceQuery = JSON.parseObject(data, BalanceQuery.class);
            return SmartResult.success(balanceQuery);
        } else {
            return SmartResult.fail(StatusMsg.StatusMsg_495);
        }
    }

    /**
     * 企业单笔资金划转_银企直联
     *
     * @param formBean
     * @return
     */
    public SmartResult singleTransfer(PinganTransferFormBean formBean) {
        SmartResult<Object> smartResult = new SmartResult<>();
        PaymentMerchant paymentMerchant = new PaymentMerchant().selectById(formBean.getPaymentMerchant());
//        String caFile = paymentMerchant.getCaFile();
//        ApiClient apiClient = ApiClient.getInstance(caFile);
        JSONObject requestBody = new JSONObject();
        requestBody.put("MrchCode", paymentMerchant.getMerchantNo());
        requestBody.put("CnsmrSeqNo", formBean.getTradeNo());
        requestBody.put("ThirdVoucher", formBean.getThirdVoucher());
        requestBody.put("CcyCode", "RMB");
        requestBody.put("OutAcctNo", paymentMerchant.getBankCard());
        requestBody.put("OutAcctName", paymentMerchant.getAccountNo());
        requestBody.put("InAcctNo", formBean.getAcctno());
        requestBody.put("InAcctName", formBean.getAcctname());
        requestBody.put("UseEx", formBean.getDescribe());
        requestBody.put("TranAmount", String.format("%.2f", formBean.getAmount()));
        requestBody.put("AddrFlag", "1");
        requestBody.put("UnionFlag", formBean.getUnionFlag());
        requestBody.put("SysFlag", "S");

        log.info("requestBody=" + requestBody);
        SdkRequest sdkRequest = new SdkRequest();
        sdkRequest.setInterfaceName("V1.0/bedl/CorSingleTransfer");
        sdkRequest.setBody(requestBody);
        HttpResult httpResult;
        try {
            httpResult = apiClient.invoke(sdkRequest);
        } catch (Exception e) {
            return SmartResult.fail(StatusMsg.StatusMsg_491);
        }
        if (null != httpResult && httpResult.isSuccess()) {
            String data = httpResult.getData();

            log.info("平安银行企业单笔资金划转_银企直联 CnsmrSeqNo: {} BEDL_4004 返回:{}", formBean.getTradeNo(), data);
            JSONObject jsonObject = JSON.parseObject(data);
            //{"Errors":[{"ErrorCode":"RE1342","ErrorMessage":":[RE1342]输入的卡号[6228480890267788514]不存在或者已经销卡                            "}],"Message":"业务处理失败（通讯成功）","Code":"E50000"}
            //错误返回报文: {"currpage":0,"msg":"操作成功","object":{"ccyCode":"RMB","cstInnerFlowNo":"","fee1":"1.00","fee2":"0.00","frontLogNo":"8043432304242759452721","hostFlowNo":"","hostTxDate":"20230424","inAcctBankName":"招商银行","inAcctName":"范磊","inAcctNo":"6214850014162827","outAcctName":"盐城如山数字科技有限公司","outAcctNo":"15000101467847","stt":"40","thirdVoucher":"PA202304241345183706","tranAmount":"0.10","unionFlag":"0"},"state":100,"totalpages":0,"totalrecords":0}
            String code = jsonObject.getString("Code");
            if (null != code) {
                smartResult.setState(256);
                JSONObject errors = (JSONObject)jsonObject.getJSONArray("Errors").get(0);
                if (null != errors && StringUtils.isNotEmpty(errors.getString("ErrorMessage"))) {
                    smartResult.setMsg(errors.getString("ErrorMessage"));
                } else {
                    smartResult.setMsg(jsonObject.getString("Message"));
                }
                return smartResult;
            }
            SingleTransfer singleTransfer = JSON.parseObject(data, SingleTransfer.class);
            return SmartResult.success(singleTransfer);
        } else {
            return SmartResult.fail(StatusMsg.StatusMsg_491);
        }
    }

    /**
     * 单笔转账指令查询_银企直联 4005
     *
     * @param formBean
     * @return
     */
    public SmartResult singleTransferQuery(PinganTransferQueryFormBean formBean) {
        SmartResult<Object> smartResult = new SmartResult<>();
        PaymentMerchant paymentMerchant = new PaymentMerchant().selectById(formBean.getPaymentMerchant());
//        String caFile = paymentMerchant.getCaFile();
//        ApiClient apiClient = ApiClient.getInstance(caFile);
        JSONObject requestBody = new JSONObject();
        requestBody.put("MrchCode", paymentMerchant.getMerchantNo());
        requestBody.put("CnsmrSeqNo", formBean.getTradeNo());
        requestBody.put("OrigThirdVoucher", formBean.getThirdVoucher());

        log.info("requestBody=" + requestBody);
        SdkRequest sdkRequest = new SdkRequest();
        sdkRequest.setInterfaceName("V1.0/bedl/CorSingleTransferQuery");
        sdkRequest.setBody(requestBody);
        HttpResult httpResult;
        try {
            httpResult = apiClient.invoke(sdkRequest);
        } catch (Exception e) {
            return SmartResult.fail(StatusMsg.StatusMsg_491);
        }
        if (null != httpResult && httpResult.isSuccess()) {
            String data = httpResult.getData();
            log.info("平安银行单笔转账指令查询_银企直联 CnsmrSeqNo: {} BEDL_4005 返回:{}", formBean.getTradeNo(), data);
            if (null != data) {
                JSONObject jsonObject = JSON.parseObject(data);
                //错误返回报文: {"OrigThirdVoucher":"PA202304241345183706","FrontLogNo":"8043432304242759452721","CstInnerFlowNo":"","CcyCode":"RMB","OutAcctBankName":"","OutAcctNo":"15000101467847","InAcctBankName":"招商银行","InAcctNo":"6214850014162827","InAcctName":"范磊","TranAmount":"0.10","UnionFlag":"0","Stt":"20","IsBack":"0","BackRem":"交易成功","Yhcljg":"000000:转账交易成功","SysFlag":"N","Fee":"1.00","TransBsn":"4004","submitTime":"20230424135221","AccountDate":"20230424","hostFlowNo":"3240792304240300031497","hostErrorCode":"000000","ProxyPayName":"","ProxyPayAcc":"","ProxyPayBankName":""}
                String code = jsonObject.getString("Code");
                if (null != code) {
                    smartResult.setState(256);
                    JSONObject errors = (JSONObject)jsonObject.getJSONArray("Errors").get(0);
                    if (null != errors && StringUtils.isNotEmpty(errors.getString("ErrorMessage"))) {
                        smartResult.setMsg(errors.getString("ErrorMessage"));
                    } else {
                        smartResult.setMsg(jsonObject.getString("Message"));
                    }
                    return smartResult;
                }
                SingleTransferQuery singleTransferQuery = JSON.parseObject(data, SingleTransferQuery.class);
                return SmartResult.success(singleTransferQuery);
            }
            return SmartResult.fail(StatusMsg.StatusMsg_491);
        } else {
            //网络异常。返回不为200
            return SmartResult.fail(StatusMsg.StatusMsg_495);
        }
    }

    /**
     * 企业大批量资金划转_银企直联
     *
     * @param formBean
     * @return
     */
    public SmartResult batchTransfer(PinganBatchTransferFormBean formBean) {
        SmartResult<Object> smartResult = new SmartResult<>();
        PaymentMerchant paymentMerchant = new PaymentMerchant().selectById(formBean.getPaymentMerchant());
//        String caFile = paymentMerchant.getCaFile();
//        ApiClient apiClient = ApiClient.getInstance(caFile);

        JSONObject requestBody = new JSONObject();
        requestBody.put("MrchCode", paymentMerchant.getMerchantNo());
        requestBody.put("CnsmrSeqNo", formBean.getTradeNo());
        requestBody.put("ThirdVoucher", formBean.getThirdVoucher());
        requestBody.put("totalCts", formBean.getTotalCts());
        requestBody.put("BSysFlag", "S");
        requestBody.put("CcyCode", "RMB");
        requestBody.put("OutAcctNo", paymentMerchant.getBankCard());
        requestBody.put("OutAcctName", paymentMerchant.getAccountNo());
        List<PinganTransferOne> transferList = formBean.getTransferList();
        List<JSONObject> hOResultSet4018R = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        for (PinganTransferOne pinganTransferOne : transferList) {
            JSONObject requestHOResult = new JSONObject();
            requestHOResult.put("SThirdVoucher", pinganTransferOne.getItemTradeNo());
            requestHOResult.put("InAcctNo", pinganTransferOne.getAcctno());
            requestHOResult.put("InAcctName", pinganTransferOne.getAcctname());
            requestHOResult.put("TranAmount", String.format("%.2f", pinganTransferOne.getTranAmount()));
            requestHOResult.put("UseEx", pinganTransferOne.getDescribe());
            requestHOResult.put("UnionFlag", pinganTransferOne.getUnionFlag());
            requestHOResult.put("AddrFlag", "1");
            totalAmount = totalAmount.add(pinganTransferOne.getTranAmount());
            hOResultSet4018R.add(requestHOResult);
        }
        //校验总金额
        if (!totalAmount.equals(formBean.getTotalAmt())) {
            return SmartResult.fail(StatusMsg.StatusMsg_490);
        }
        requestBody.put("totalAmt", String.format("%.2f", formBean.getTotalAmt()));
        requestBody.put("HOResultSet4018R", hOResultSet4018R);
        log.info("requestBody=" + requestBody);
        SdkRequest sdkRequest = new SdkRequest();
        sdkRequest.setInterfaceName("V1.0/bedl/CorBatchTransfer");
        sdkRequest.setBody(requestBody);
        HttpResult httpResult = apiClient.invoke(sdkRequest);
        if (httpResult.isSuccess()) {
            String data = httpResult.getData();
            log.info("平安银行企业批量资金划转_银企直联 CnsmrSeqNo: {} BEDL_4018 返回:{}", formBean.getTradeNo(), data);
            JSONObject jsonObject = JSON.parseObject(data);
            //错误返回报文: {"currpage":0,"msg":"操作成功","object":{"ccyCode":"RMB","cstInnerFlowNo":"","fee1":"1.00","fee2":"0.00","frontLogNo":"8043432304242759452721","hostFlowNo":"","hostTxDate":"20230424","inAcctBankName":"招商银行","inAcctName":"范磊","inAcctNo":"6214850014162827","outAcctName":"盐城如山数字科技有限公司","outAcctNo":"15000101467847","stt":"40","thirdVoucher":"PA202304241345183706","tranAmount":"0.10","unionFlag":"0"},"state":100,"totalpages":0,"totalrecords":0}
            String code = jsonObject.getString("Code");
            if (null != code) {
                smartResult.setState(256);
                JSONObject errors = (JSONObject)jsonObject.getJSONArray("Errors").get(0);
                if (null != errors && StringUtils.isNotEmpty(errors.getString("ErrorMessage"))) {
                    smartResult.setMsg(errors.getString("ErrorMessage"));
                } else {
                    smartResult.setMsg(jsonObject.getString("Message"));
                }
                return smartResult;
            }
            BatchTransfer batchTransfer = JSON.parseObject(data, BatchTransfer.class);
            return SmartResult.success(batchTransfer);
        } else {
            return SmartResult.fail(StatusMsg.StatusMsg_489);
        }
    }

    /**
     * 批量转账指令查询_银企直联 4015
     *
     * @param formBean
     * @return
     */
    public SmartResult batchTransferQuery(PinganBatchTransferQueryFormBean formBean) {
        SmartResult<Object> smartResult = new SmartResult<>();
        PaymentMerchant paymentMerchant = new PaymentMerchant().selectById(formBean.getPaymentMerchant());
//        String caFile = paymentMerchant.getCaFile();
//        ApiClient apiClient = ApiClient.getInstance(caFile);
        JSONObject requestBody = new JSONObject();
        requestBody.put("MrchCode", paymentMerchant.getMerchantNo());
        requestBody.put("CnsmrSeqNo", formBean.getTradeNo());
        requestBody.put("OrigThirdVoucher", formBean.getThirdVoucher());

        log.info("requestBody=" + requestBody);
        SdkRequest sdkRequest = new SdkRequest();
        sdkRequest.setInterfaceName("V1.0/bedl/CorBatchTransferQuery");
        sdkRequest.setBody(requestBody);

        HttpResult httpResult = apiClient.invoke(sdkRequest);
        if (httpResult.isSuccess()) {
            String data = httpResult.getData();
            log.info("平安银行企业批量转账指令查询_银企直联 CnsmrSeqNo: {} BEDL_4015 返回:{}", formBean.getTradeNo(), data);
            if (null != data) {
                JSONObject jsonObject = JSON.parseObject(data);
                //错误返回报文: {"OrigThirdVoucher":"PA202304241345183706","FrontLogNo":"8043432304242759452721","CstInnerFlowNo":"","CcyCode":"RMB","OutAcctBankName":"","OutAcctNo":"15000101467847","InAcctBankName":"招商银行","InAcctNo":"6214850014162827","InAcctName":"范磊","TranAmount":"0.10","UnionFlag":"0","Stt":"20","IsBack":"0","BackRem":"交易成功","Yhcljg":"000000:转账交易成功","SysFlag":"N","Fee":"1.00","TransBsn":"4004","submitTime":"20230424135221","AccountDate":"20230424","hostFlowNo":"3240792304240300031497","hostErrorCode":"000000","ProxyPayName":"","ProxyPayAcc":"","ProxyPayBankName":""}
                String code = jsonObject.getString("Code");
                if (null != code) {
                    smartResult.setState(256);
                    JSONObject errors = (JSONObject)jsonObject.getJSONArray("Errors").get(0);
                    if (null != errors && StringUtils.isNotEmpty(errors.getString("ErrorMessage"))) {
                        smartResult.setMsg(errors.getString("ErrorMessage"));
                    } else {
                        smartResult.setMsg(jsonObject.getString("Message"));
                    }
                    return smartResult;
                }
                return SmartResult.success(data);
            }
            return SmartResult.fail(StatusMsg.StatusMsg_494);
        } else {
            return SmartResult.fail(StatusMsg.StatusMsg_494);
        }
    }

}
